//
//  LKTreeBenefitViewController.m
//  Mideleague_Agent
//
//  Created by Zhiwang on 2020/9/14.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKTreeBenefitViewController.h"
#import "LKBaseView.h"
@interface LKTreeBenefitViewController ()<MYTreeTableViewControllerParentClassDelegate,GetContentInformation>

@property(nonatomic,strong)NSArray <MYTreeItem *> *selectItems;

@end

@implementation LKTreeBenefitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.isShowCheck) {
        self.navigationItem.title = @"选择交接人";
        [self setNavgationRightBtn];
    }else{
        self.navigationItem.title = @"下级收益明细";
    }
    [self setNavgationBackBtn];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.classDelegate = self;
    [self getAllBenfitListData];
    // 请求数据
//    [self requestData];


}
/**
 设置返回按钮样式
 */
-(void)setNavgationBackBtn{
    LKNavBackButton *button = [[LKNavBackButton alloc] init];
    [button setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setImage:[UIImage imageNamed:@"backArrow"] forState:UIControlStateNormal];
    [button setTitleColor:blueDefault forState:UIControlStateNormal];
    button.bounds = CGRectMake(0, 0, 100, 40);
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
- (void)back
{
    NSArray *viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self) {
            //push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{
        //present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
-(void)setNavgationRightBtn{
    WS(weakSelf)
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 64, 24);
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    [rightBtn setTitleColor:COLOR_HEX(0xF86747) forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 12];
    rightBtn.layer.cornerRadius = 15;
    rightBtn.layer.masksToBounds = YES;
    [rightBtn addTarget:self action:@selector(handAction:) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.layer.borderColor = COLOR_HEX(0xF86747).CGColor;
    rightBtn.layer.borderWidth = 1;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
-(void)handAction:(UIButton *)btn{
    WS(weakSelf);
      if (self.selectItems.count == 0) {
          [SVProgressHUD showInfoWithStatus:@"请选择交接人"];
          return ;
      }
          UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否确认交接" message:@"" preferredStyle:UIAlertControllerStyleAlert];
          [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
      
          }]];
          [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
              [SVProgressHUD show];
              NSMutableString *merchatIds = [[NSMutableString alloc] init];
              for (NSInteger i = 0; i < weakSelf.handleShopsArray.count; i++) {
                  LKMyShoplistModel *merchatModel = weakSelf.handleShopsArray[i];
                  [merchatIds appendString:merchatModel.mch_uid];
                  if (i != weakSelf.handleShopsArray.count - 1) {
                      [merchatIds appendString:@","];
                  }
              }
              MYTreeItem *item = [weakSelf.selectItems firstObject];
              NSString *agent_uid = item.data[@"agent_uid"];
              NSDictionary *param = @{@"mid_arr":merchatIds,@"list":agent_uid,@"operator_id":[LKUserInforTool account].uid,@"user_name":[LKUserInforTool account].user_name};
              [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyHandoverMerchantUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {

              } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                  if ([responseObject[@"code"] isEqual:@"success"]) {
                      [SVProgressHUD showInfoWithStatus:@"交接完成"];
                      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                           [weakSelf.navigationController popViewControllerAnimated:YES];
                          [[NSNotificationCenter defaultCenter] postNotificationName:@"handMerchantOverNotice" object:nil];
                      });

                  }else{
                      [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                  }

              } failure:^(NSString * _Nullable errorMessage) {
                  [SVProgressHUD showInfoWithStatus:errorMessage];
              }];
          }]];
          [self presentViewController:alert animated:YES completion:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;

}
// 点击右上角 提交
- (void)commitItemClick {
    [self prepareCommit];
}

// 点击右上角 全选
- (void)allCheckItemClick {
    [self checkAllItem:YES];
}

// 点击右上角 全部展开
- (void)allExpandItemClick {
    [self expandAllItem:YES];
}



#pragma mark - MYTreeTableViewControllerParentClassDelegate

- (void)refreshTableViewController:(MYTreeTableViewController *)tableViewController {
    [self getAllBenfitListData];
}

- (void)tableViewController:(MYTreeTableViewController *)tableViewController checkItems:(NSArray<MYTreeItem *> *)items {
    
    // 这里加一个隔离带目的是可以在这里做出个性化操作，然后再将数据传出
    if ([self.delegate respondsToSelector:@selector(tableViewController:checkItems:)]) {
        [self.delegate tableViewController:self checkItems:items];
    }
    self.selectItems = items;
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchBarDidBeginEditingInTableViewController:(MYTreeTableViewController *)tableViewController {
    NSLog(@"点击了搜索栏");
}

- (void)tableViewController:(MYTreeTableViewController *)tableViewController didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"点击了第 %ld 行", (long)indexPath.row);
}

- (void)tableViewController:(MYTreeTableViewController *)tableViewController didSelectCheckBoxRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"点击了第 %ld 行的 checkbox", (long)indexPath.row);
}


/**
 取消的代理放
 */
-(void)ContentPickerCancleActionAndPickerView:(UIPickerView *)pickeView{
    [self.sorcepickerView removeFromSuperview];
}

- (void)getContentInformation:(NSString *)sex AndPickerView:(UIPickerView *)pickeView {
    [self.sorcepickerView removeFromSuperview];
    [self.timeBtn setTitle:sex forState:UIControlStateNormal];
    [self getAllBenfitListData];
    NSLog(@"选中%@",sex);
}

/// 获取我的下级的代理的收益数据
-(void)getAllBenfitListData{
    [SVProgressHUD show];
    NSDictionary *param;
   if (self.isShowTimeChoose) {
      param = @{@"token":[LKUserInforTool account].token,@"uid":[LKUserInforTool account].uid,@"time":self.timeBtn.currentTitle};
   }else{
       NSString *currentMonth = [[[NSString getCurrentTime] componentsSeparatedByString:@" "] firstObject];
      param = @{@"token":[LKUserInforTool account].token,@"uid":[LKUserInforTool account].uid,@"time":[currentMonth substringToIndex:7]};
   }
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyTreeBenefitUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject[@"code"] isEqualToString:@"success"]) {
            NSArray *dataArray = responseObject[@"data"];
            NSMutableSet *items = [NSMutableSet set];
            for (NSDictionary *data in dataArray) {
                MYTreeItem *item = [[MYTreeItem alloc] initWithName:[NSString judegeIsNullAndTransform:data[@"agent_name"]]
                                                                 ID:[NSString stringWithFormat:@"%@", data[@"id"]]
                                                           parentID:[NSString stringWithFormat:@"%@", data[@"agent_pid"]]
                                                            orderNo:nil
                                                               type:nil
                                                             isLeaf:NO
                                                               data:data];
                [items addObject:item];
            }
            // ExpandLevel 为 0 全部折叠，为 1 展开一级，以此类推，为 NSIntegerMax 全部展开
            self.manager = [[MYTreeTableManager alloc] initWithItems:items andExpandLevel:0];
            [self prepareCommit];
            NSLog(@"cao=%@",self.manager.allItems);
        }else{
           [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }

    } failure:^(NSString * _Nullable errorMessage) {
        [SVProgressHUD dismiss];
    }];
}
-(void)handleMerchantAction{
    [SVProgressHUD show];
    NSString *merchatIds;
    for (LKMyShoplistModel *merchatModel in self.handleShopsArray) {
        merchatIds = [merchatIds stringByAppendingFormat:@"%@",merchatModel.mch_id];
    }
    NSDictionary *param = @{@"mid_arr":merchatIds,@"agent_id":@""};
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyHandoverMerchantUrl header:@"" parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
